iT邦幫忙

0

Spring @Component 註解初階應用 :Ioc (Inversion of Control 控制反轉)

  • 分享至 

  • xImage
  •  

Inversion of Control 控制反轉

先講正向注入
1.interface
2.Polymorphism

public interface Printer {
    void print(String message);
}
public class HpPrinter implements Printer{
@Override
public void print (String message){
System.out.println("HP印表機:"+message);
}
}
public class Teacher{
private Printer printer = new HpPrinter();
public void teach(){
printer.print("I'm a teacher")
}
}
public class Student {
private Printer printer = new HpPrinterI();
public void learn(){
printer.print("I'm a student");
}
}

ioc 開始!!!
@Component  
1.只能+在CLASS上
2.可以將該CLASS 變成 SPRING 容器所管理的object
3.它就變成bean了 (咖啡豆) :Bean hpPrinter   , H要用小寫
4.等於統一在spring 容器中 新增物件: Printer hpPrinter = new  HpPrinter();
5.Teacher 也要變成bean
6. Teacher 可用@Autowired來依賴注入 Bean hpPrinter 進入

@Component
public class HpPrinter implements Printer {
@Override
public void print(String message) {
System.out.println("HP印表機:" +message);
}
}
public calss Teacher {
private Printer printer = new HpPrinter();
public void teach () {
printer.print("i'm a teacher");
}
}

@Component
public class Teacher {
@Autowired
private Printer printer;
public void teach() {
printer.print("I'm a teacher");
}
}

console輸出結果: HP印表機I'm a teacher

Spring IOc 運作流程完畢~~~~~~~~~~~~~~~~~~~~~~

打完收工~~
我又拯救了這個悶熱的下午~ 


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言